package com.qingke.hibernate.oneday.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import com.qingke.hibernate.oneday.pojo.Apartment;

public class ApartmentDao {
	private Session session;
	
	public ApartmentDao(Session session) {
		this.session = session;
	}
	
	public List<Apartment> listApartments() {
		Query<Apartment> query = session.createQuery("from Apartment", Apartment.class);
		return query.getResultList();
	}
	
	public Apartment getApartmentById(int id) {
		return session.get(Apartment.class, id);
	}

	public void insert(Apartment apartment) {
		Transaction ts = session.beginTransaction();
		try {
			session.save(apartment);
			session.flush();
			ts.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
			ts.rollback();
		}
	}

	public void update(Apartment apartment) {
		Transaction ts = session.beginTransaction();
		try {
			session.update(apartment);
			ts.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
			ts.rollback();
		}
	}

	public void delete(Apartment apartment) {
		Transaction ts = session.beginTransaction();
		try {
			session.delete(apartment);
			ts.commit();
		} catch (HibernateException he) {
			he.printStackTrace();
			ts.rollback();
		}
	}
}
